import axios from "axios";
import req from "./axios"

const rs = require('jsrsasign');
const prvKey = '-----BEGIN PRIVATE KEY-----MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAL5ydh/Zrk0XnAL5cfDi6f1896TRJOUm+/t7onEd1duQ/wJeyOeICX+QycWNJbkHXLi+sscUKhZeH6lFVNCNRXrh8n/aCFU90Epq8RM5LMNj9rquaRfHV5lxxuVZucEy6hYxdpL/4TxbI5qwJ9T+TTIXlK7W1pns+FMGSBMXnLKDAgMBAAECgYAEi36+K9e5B0M13vYVJZUn83+Fc2hJ/7ArxDuQL4IXB1LOn6xzug9f9/iYulGYJNDVp9dkYNrQRdbDl1/6yiRKS+gmTtgP07SIVzWMG4Sz4NxvGo5qeznFlkcbEYSeuWlIGBTAps/R3dw+cx+pUHGg6jNfcrVAHeWu23yOy9puoQJBANzTgYbRwDgF2ckrhuaXn8Cv8h3HojhkMYM83kPGCgdzr6U6MJddXkO0LKbnWfjg/CgvQ4QdTZ5CKa3U+kyzucUCQQDcyDTVHet8PQKt5w0hWFkR3/8SrGt3/mdE2a8/5+QDhd4j/rg/2DeDxnVXeV7Zuo5aEf+bSOBqkgcbp8GlY6enAkEAqdDExMa8SNjG+BrO7LkhEu67BAenSjJSmRfP3NKIl95w7mDnSR92BB6kT92NpQRvJP/jrc9TBybeIl2r9hwn+QJAZ/ta9qyaxe6uHl1dj8DeYk7PAWp3SxJkbMbhhQWgHBCmaOmEuX0J2GRVy5b8FyuH89/aNLaEC20vL9U4nL5srQJBAIyDhMdVco7llsdqNveks5tJMNWU8CAWWzBlW+r0nvghc7tzPNXRe6Z8rNQ0+vwlFZ6UZt6GLvdvlomOOyuz20k=-----END PRIVATE KEY-----'


const requests = axios.create({
    baseURL: "https://www.aqijiaoyu.com/JiaoGuiWebApi/api/",
    timeout: 5000,
    headers: {
        'Content-Type': "application/json; charset=utf-8"
    }
})

requests.interceptors.request.use(
    async config => {
        let token = localStorage.getItem("token")
        if (!token) {
            token = await getToken()
            localStorage.setItem("token", token)
        }
        config.headers['Authorization'] = 'Bearer ' + token;
        return config
    }
);

requests.interceptors.response.use(
    async response => {
        console.log(response)
        if (response.status === 401) {
            console.log(response.request)
            let token = await getToken();
            localStorage.setItem("token", token)
            //重新请求
            return requests.post(response.config.baseURL + response.config.url,response.config.data)
        }
        return response;
    },
)

async function getToken() {
    let preTokenRes = await req.post("Authentication/GetPreToken")
    let preToken = preTokenRes.data['PreToken']
    let sign = signPreToken(preToken)
    let requestToken = await req.post('Authentication/RequestToken', {
        username: preToken,
        password: sign
    });
    return requestToken.data['token']
}

function signPreToken(preToken) {
    let signature = new rs.KJUR.crypto.Signature({alg: "SHA256withRSA", prvkeypem: prvKey})
    signature.updateString(preToken)
    let a = signature.sign()
    return rs.hextob64(a)
}


export default requests
